package com.samp.bblock.test.service;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.samp.bblock.core.exception.DaoException;
import com.samp.bblock.core.exception.ServiceException;
import com.samp.bblock.test.dao.ConfigInfoDAO;
import com.samp.bblock.test.dto.ConfigInfoDTO;

@Service("configInfoService")
public class ConfigInfoService {
	
	
	
	@Resource
	private ConfigInfoDAO configInfoDAO;
	
	private static final Logger logger = LoggerFactory.getLogger(ConfigInfoService.class);

	
		public String queryConfigInfo(ConfigInfoDTO configInfoDTO)
													throws ServiceException{
			try {
				ConfigInfoDTO con =  configInfoDAO.queryConfigInfo(configInfoDTO);
				if( con == null || StringUtils.isEmpty(con.getConfigValue())){
					return null;
				}
				return con.getConfigValue();
			} catch (DaoException e) {
				logger.error("查询配置信息出错",e);
				throw new ServiceException("查询配置信息出错",e);
			}
		}
		
		@Transactional(rollbackFor=Exception.class)
		public void testTransaction(String configKey,String catchException ) throws ServiceException{
			logger.info("testTransaction start");
			logger.info("testTransaction insert two records.");
			ConfigInfoDTO conf1 = new ConfigInfoDTO();
			conf1.setConfigKey(configKey);
			conf1.setConfigType("test01");
			conf1.setConfigValue("test01");
			ConfigInfoDTO conf2 = new ConfigInfoDTO();
			conf2.setConfigKey(configKey);
			conf2.setConfigType("test02");
			conf2.setConfigValue("test02");
			try {
				configInfoDAO.insertConfigInfo(conf1);
				configInfoDAO.insertConfigInfo(conf2);
			} catch (DaoException e) {
				throw new ServiceException(" error in insert.", e);
			}
			String value = queryConfigInfo(conf1);
			if( !"test01".equals(value) ){
				throw new ServiceException("value is not the right ont, value="+value);
			}
			logger.info("testTransaction query sucess.");
			ConfigInfoDTO conf3 = new ConfigInfoDTO();
			try {
				configInfoDAO.insertConfigInfo(conf3);
			} catch (Exception e) {
				if( "yes".equals(catchException) ){
					logger.info("catch  exception, not rollback");
				}else{
					logger.info("error, roll  back");
					throw new ServiceException(" empty config info", e);
				}
			}
			logger.info("testTransaction end");
		}
}
